<?php
require_once(dirname(dirname(__FILE__)).'/libs/db.class.php');
class Product
{
    public $db;
    function __construct()
    {
        $this->db = new DB();
    }
    /*
        商品列表
    */
    function index()
    {
        $output=['errcode'=>0,'msg'=>'success'];
        $sql = "select id,name,cover,price,market_price,sales_volume,brand,category from products";
        $list = $this->db->query($sql);
        $output['list']=$list;
        echo json_encode($output);
    }
    /*
        新增商品
    */
    function add(){
        $output=['errcode'=>0,'msg'=>'success'];
        if($data=$_POST){
            $data['createtime']=date('Y-m-d H:i:s');
            $str=$this->arr2str($data);
            $sql="insert into products set {$str}";    
            $this->db->query($sql);
            $output['sql']=$sql;
        }
        echo json_encode($output);
    }
    
    /*
        编辑商品
    */ 
    function edit(){
        $output=['errcode'=>0,'msg'=>'success'];
        $id=$_GET['id'];
        if($data=$_POST){
            $str=$this->arr2str($data);
            $sql="update products set {$str} where id={$id}";    
            $this->db->query($sql);
            $output['sql']=$sql;
        }
        echo json_encode($output);
    }

    function detail(){
        $output=['errcode'=>0,'msg'=>'success'];
        if($id=$_GET['id']){
            $sql="select * from products where id={$id}";    
            $list=$this->db->query($sql);
            $output['data']=$list[0];
        }
        echo json_encode($output);
    }

    /*
        删除商品
    */ 
    function del(){
        $output=['errcode'=>0,'msg'=>'success'];
        if($id=$_GET['id']){
            $sql="delete from products where id={$id}";    
            $this->db->query($sql);
            $output['sql']=$sql;
        }else{
            $output['errcode']=1;
            $output['msg']='参数错误';
        }
        echo json_encode($output);
    }

    /*
        工具函数:query2str
        name=zs&age=20=>name='zs',age=20
    */
    function arr2str($arr){
        $str='';
        foreach($arr as $key=>$val){
            if($key=='editorValue'){
                $str.="introduce='{$val}',";
            }else{
                $str.="{$key}='{$val}',";
            }
        }
        $str=substr($str,0,-1);
        return $str;
    }

   
}

